"""
工具函数
"""

import requests
from lxml import etree
from collectcookiee.settings import headers


def medalGotList(cookie):
    """获取我的所有徽章"""
    url = 'https://me.csdn.net/api/user/getMedalGotList?pageSize=20&pageNum=1'
    headers['cookie'] = cookie
    response = requests.get(url, headers=headers, timeout=8)
    if response.status_code == requests.codes.ok:
        medal_list = [item['image'].split('/')[-1] for item in response.json()['data']['list']]
        return medal_list
    else:
        return None


def user_info(cookie):
    """获取用户个人信息"""
    url = 'https://me.csdn.net/api/user/show'
    headers['cookie'] = cookie
    response = requests.post(url, headers=headers, timeout=8)
    if response.status_code == requests.codes.ok:
        data = response.json().get('data')
        result = {
            'avatarurl': data.get('avatarurl'),
            'nickname': data.get('nickname'),
            'years': data.get('years'),
            'url': f'https://blog.csdn.net/{data.get("username")}',
            'model_list': medalGotList(cookie)
        }
        return result
    else:
        return None


def check_cookie_status(cookie):
    """检查cookie状态"""
    url = 'https://passport.csdn.net/v1/api/check/userstatus'
    headers['cookie'] = cookie
    response = requests.post(url, headers=headers, timeout=8)
    if response.status_code == requests.codes.ok:
        return response.json().get('status')
    else:
        return None


def get_article_title(url):
    """获取文章标题"""
    response = requests.get(url, headers=headers, timeout=8)
    if response.status_code == requests.codes.ok:
        content = response.text
        html = etree.HTML(content)
        return html.xpath('//h1[@id="articleContentId"]/text()')[0]
    else:
        return None


def like_comment_script(url):
    """点赞评论脚本"""
    pass
